package com.sy.cloud.guess.controller;

import com.alibaba.fastjson.JSONObject;
import com.gok.pay.wx.WXPayUtil;
import com.google.gson.Gson;
import com.sy.cloud.guess.model.GiftExchange;
import com.sy.cloud.guess.model.JOrder;
import com.sy.cloud.guess.model.PayOrder;
import com.sy.cloud.wechat.model.WechatUser;
import com.sy.cloud.wechat.model.Wxuser;
import com.sy.common.model.Juejinuser;
import com.sy.common.service.IBaseService;
import com.sy.common.service.IDbService;
import com.sy.common.service.ITestService;
import com.sy.common.util.Funutil;
import com.sy.shiro.UsernameToken;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.subject.Subject;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.test.annotation.Rollback;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.*;

/**
 * Created by mac on 2017/11/28.
 */
@Controller
@Slf4j
@RequestMapping("/login")
public class LoginController {

    @Resource
    private IDbService dbService;

    @Resource
    private IBaseService baseService;

    @Resource
    private ITestService testService;

    @Resource
    private CookieController cookieController;

    @RequestMapping(value = "/regphone", method = RequestMethod.POST,produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public
    @ResponseBody
    @Rollback(false)
    JSONObject regphone( HttpServletRequest request, HttpServletResponse response, Model model) throws Exception {
        JSONObject jsonObject = new JSONObject();

        String passwd = request.getParameter("pwd");
        String phone = request.getParameter("phone");
        String veri = request.getParameter("vericode");

        String shareid = "";
        if (request.getSession().getAttribute("shareid") != null) {
            shareid = (String) request.getSession().getAttribute("shareid");
        }
        if (veri != null) {
            String sveri = request.getSession().getAttribute("vericode").toString();
            if (!veri.equals( sveri )) {
                jsonObject.put("message", "验证码错误");
                jsonObject.put("status", "0");
                return jsonObject;
            }
        }else{
            jsonObject.put("message", "验证码不能为空");
            jsonObject.put("status", "0");
            return jsonObject;
        }

        StringBuffer hql = new StringBuffer();
        hql.append("From Juejinuser where phone='");
        hql.append(phone);
        hql.append("'");
        List<Juejinuser> juejinuserList = baseService.listQuery(hql.toString(), Juejinuser.class);

        if (juejinuserList.size() > 0) {
            jsonObject.put("message", "不能重复注册");
            jsonObject.put("status", "0");
            return jsonObject;
        }

        Funutil funutil = new Funutil();
        passwd = funutil.encodeByMD5(passwd);
        Juejinuser juejinuser = new Juejinuser();
        juejinuser.setPhone(phone);
        juejinuser.setPassword(passwd);
        if (shareid != "") {
            Juejinuser parentUser = testService.getJueUserById( shareid );
            if( parentUser == null ){
                jsonObject.put("message", "上级id错误");
                jsonObject.put("status", "0");
                return jsonObject;
            }
            juejinuser.setShareid(Integer.parseInt(shareid));
            // 查找token
            juejinuser.setToken( parentUser.getToken() );
        }


        Cookie cookie = cookieController.getCookieByName(request,"openId");
        String openId = "";
        if( cookie != null ){
            openId = (String) cookie.getValue();
            WechatUser wechatUser = testService.getWechatInfo(openId);
            log.info( "cookie获得的openId是===="+openId );
            if (wechatUser != null) {
                juejinuser.setHeadimgurl(wechatUser.getHeadimgurl());
                juejinuser.setUsername(wechatUser.getWechat_name());
            }
        }else{
            Cookie cookie1 = cookieController.getCookieByName(request, "headimg");
            if( cookie1 != null ){
                juejinuser.setHeadimgurl( cookie1.getValue() );
                cookie1 = cookieController.getCookieByName(request, "nickname");
                juejinuser.setUsername( cookie1.getValue() );
            }
        }

        juejinuser.setCreate_time( System.currentTimeMillis()/1000 +"" );



        testService.addUser(juejinuser);

        jsonObject.put("message", "success");
        jsonObject.put("status", "1");

        //  给用户登录
        SecurityUtils.getSubject().login(new UsernameToken(phone, passwd, (long) 0));


        // 判断是否有赠送英雄卡start
        Cookie cookie1 = cookieController.getCookieByName(request,"knapsackadd");
        Cookie cookie2 = cookieController.getCookieByName(request,"knapsacksec");
        if( (cookie1 != null) && (cookie2 != null) ){
            cookie1.setMaxAge(0);
            cookie2.setMaxAge(0);
            response.addCookie( cookie1 );
            response.addCookie( cookie2 );// 清空cookie
            testService.cardAdd( cookie2.getValue(), cookie1.getValue(), juejinuser );
        }
        // 判断是否有赠送英雄卡end


        cookieController.addCookie(response,"phone",phone);

        // 获取用户信息
        StringBuilder hql1 = new StringBuilder();
        hql1.append("From Juejinuser where phone = ");
        hql1.append(phone);

        List<Juejinuser> juejinuserList1 = baseService.listQuery(hql1.toString(), Juejinuser.class);
        Juejinuser juejinuser1 = juejinuserList1.get(0);

        request.setAttribute("user", juejinuser1);

        return jsonObject;
    }

    @RequestMapping(value = "/loginaction", method = RequestMethod.POST)
    public String loginaction(HttpServletRequest request, HttpServletResponse response) {
        // 朋友圈分享
        String url = request.getScheme() + "://" + request.getServerName() + request.getRequestURI() + "?" + request.getQueryString();
        if( request.getQueryString() == null ){
            url = request.getScheme() + "://" + request.getServerName() + request.getRequestURI() ;
        }
        long cur =  System.currentTimeMillis();
        Wxuser wxuser1 = testService.getWxByWxid( "gh_6dadebf53ec2" );
        Map<String, String> mapreq = new HashMap();
        String non = WXPayUtil.generateUUID();
        mapreq.put("noncestr", non);
        mapreq.put("jsapi_ticket", wxuser1.getTicket() );
        mapreq.put("timestamp", cur + "" );
        mapreq.put("url", url );
        String signStr = "";
        try {
            signStr = Funutil.generateSignature( mapreq );
        } catch (Exception e) {
            e.printStackTrace();
        }
        mapreq.put("signature", signStr );
        String gsond = new Gson().toJson(mapreq);
        request.setAttribute( "signPackage", gsond );





        String passwd = request.getParameter("pwd");
        String phone = request.getParameter("phone");
        passwd = request.getParameter("pwd");
        phone = request.getParameter("phone");

        Funutil funutil = new Funutil();
        passwd = funutil.encodeByMD5(passwd);
        log.info("密码" + passwd);

        JSONObject jsonObject = new JSONObject();

        try {
            SecurityUtils.getSubject().login(new UsernameToken(phone, passwd, (long) 0));
        } catch (AuthenticationException e) {
            // 登录失败
            request.setAttribute("message", "账号密码错误");
            request.setAttribute("status", "0");
            return "login";
        }


        // 登录成功
        request.setAttribute("message", "success");
        request.setAttribute("status", "1");

        cookieController.addCookie(response,"phone",phone);


        StringBuilder hql = new StringBuilder();
        hql.append("From Juejinuser where phone = ");
        hql.append(phone);

        List<Juejinuser> juejinuserList = baseService.listQuery(hql.toString(), Juejinuser.class);
        Juejinuser juejinuser = juejinuserList.get(0);
        log.info("登录action是的userid"+juejinuser.getId());
        request.setAttribute( "userid", juejinuser.getId() );
        request.setAttribute( "token", juejinuser.getToken() );

        Cookie cookie = cookieController.getCookieByName(request,"openId");
        if( cookie != null ){
            String openId = cookieController.getCookieByName(request,"openId").getValue();
            log.info( "登录时更新昵称和头像时的openId"+openId );
            WechatUser wechatUser = testService.getWechatInfo(openId);
            if (wechatUser != null) {
                juejinuser.setHeadimgurl(wechatUser.getHeadimgurl());
                juejinuser.setUsername(wechatUser.getWechat_name());
            }
        }else{
            Cookie cookie1 = cookieController.getCookieByName(request, "headimg");
            if( cookie1 != null ){
                juejinuser.setHeadimgurl( cookie1.getValue() );
                cookie1 = cookieController.getCookieByName(request, "nickname");
                juejinuser.setUsername( cookie1.getValue() );
            }
        }

        testService.addUser(juejinuser);


        // 判断是否有赠送英雄卡
        Cookie cookie1 = cookieController.getCookieByName(request,"knapsackadd");
        Cookie cookie2 = cookieController.getCookieByName(request,"knapsacksec");
        if( (cookie1 != null) && (cookie2 != null) ){
            cookie1.setMaxAge(0);
            cookie2.setMaxAge(0);
            response.addCookie( cookie1 );
            response.addCookie( cookie2 );// 清空cookie
            log.info(cookie1.getValue());
            log.info(cookie2.getValue());
            Gson gson = new Gson();
            log.info( gson.toJson( juejinuser ) );
            testService.cardAdd( cookie2.getValue(), cookie1.getValue(), juejinuser );
        }



        request.setAttribute("user", juejinuser);
        Gson gson = new Gson();


        String historyPage = request.getParameter("historyPage");
        if( historyPage != null ){
            if( historyPage.equals("knapsack") ){
                return "bagview";
            }
        }



        return "index";

    }

    // 分享时会分享/login/loginaction
    @RequestMapping(value = "/loginaction", method = RequestMethod.GET)
    public String loginaction22( HttpServletRequest request, HttpServletResponse response) {
        UsernameToken token = testService.getUser();
        if( token != null ){
            log.info("用户userid"+token.getUserId());
            request.setAttribute( "userid", token.getUserId() );
        }

        return "index";
    }


    /*
    * 获取游戏系统账号信息
    * */
    @RequestMapping(value = "/getUserInfo", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ResponseBody
    public JSONObject getUserInfo(HttpServletRequest request, HttpServletResponse response) throws IOException {
        JSONObject result = new JSONObject();
        Gson gson = new Gson();
        // 获取用户信息
        UsernameToken token = testService.getUser();
        Juejinuser juejinuser1 = new Juejinuser();
        if (token != null) {
            // 有session缓存
            juejinuser1 = testService.getJueUserById( token.getUserId().toString() );
            if( juejinuser1 == null ){
                // 执行退出操作
                loginaction(request,response);
                result.put("status", 0);
                result.put("message", "nologin");
                return result;
            }
        } else {
            // 没有登录
            if( request.getSession().getAttribute("headimg") != null ){

                String headimg = request.getSession().getAttribute("headimg").toString();

                juejinuser1.setHeadimgurl( headimg );
                juejinuser1.setCoin(0.0);
                juejinuser1.setUsername( request.getSession().getAttribute("nickname").toString() );
                result.put("userinfo", juejinuser1);
                return result;
            }





            result.put("status", 0);
            result.put("message", "nologin");
            return result;
//            return gson.toJson( result );
        }
        // 获得用户的下注情况。未结算的

        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("From JOrder where type = 0 and userid = ");
        stringBuilder.append(juejinuser1.getId());
        List<JOrder> jOrders = baseService.listQuery(stringBuilder.toString(), JOrder.class);
        Map<String, Integer> mapBet = new HashMap<String, Integer>();
        for (int i = 0; i < jOrders.size(); i++) {
            JOrder jOrder = jOrders.get(i);
            if (mapBet.containsKey(jOrder.getCapital().toString())) {
                mapBet.put(jOrder.getCapital().toString(), (mapBet.get(jOrder.getCapital().toString()) + jOrder.getAmount()));
            } else {
                mapBet.put(jOrder.getCapital().toString(), jOrder.getAmount());
            }
        }


        request.setAttribute("user", juejinuser1);
        result.put("beginfo", mapBet);
        result.put("userinfo", juejinuser1);
        result.put("status", "1");
        return result;
//        return gson.toJson( result );
    }


    /*
   * 获取游戏系统账号信息
   * */
    @RequestMapping(value = "/getUserInfo2", method = RequestMethod.GET)
    @ResponseBody
    public JSONObject getUserInfo2(HttpServletRequest request, HttpServletResponse response) {

        JSONObject result = new JSONObject();
        result.put("retyr", "1dufaoisd");
        Gson gson = new Gson();
//        return gson.toJson( result );
//        return "dfs";
        return result;
    }

    /*
    * 获取微信昵称和头像
    * */
    @RequestMapping(value = "/getWechatInfo", method = RequestMethod.GET)
    public void getWechatInfo(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String open_id = (String) request.getSession().getAttribute("openId");

        WechatUser wechatUser = testService.getWechatInfo(open_id);

        if (wechatUser == null) {
            response.getWriter().print("none");
        } else {
            Gson gson = new Gson();
            response.getWriter().print(gson.toJson(wechatUser));
        }
    }

    @RequestMapping(value = "/loginout", method = RequestMethod.GET)
    @ResponseBody
    public String loginout(HttpServletRequest request, HttpServletResponse response) throws IOException {
        Subject subject = SecurityUtils.getSubject();
        if (subject.isAuthenticated()) {

            java.util.Enumeration   e   =   request.getSession().getAttributeNames();

            while( e.hasMoreElements())   {
                String sessionName=(String)e.nextElement();

                log.info( sessionName + "====="  + request.getSession().getAttribute(sessionName) );
            }

            subject.logout(); // session 会销毁，在SessionListener监听session销毁，清理权限缓存
            // 清空cookie
            Cookie cookie = cookieController.getCookieByName(request,"phone");
            cookie.setMaxAge(0);
            response.addCookie(cookie);
            return "ok";
        }
        return "ok";
    }

    /**
     * 玩家个人的充值记录
     * @param request
     * @param response
     * @return
     * @throws IOException
     */
    @RequestMapping(value = "/payrecord", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ResponseBody
    public JSONObject payrecord(HttpServletRequest request, HttpServletResponse response) throws IOException {
        UsernameToken usernameToken = testService.getUser();
        if (usernameToken == null) {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("status", "0");
            jsonObject.put("message", "nologin");
            return jsonObject;
        }
        String page = request.getParameter("page");
        if (page.length() == 0) {
            page = "1";
        }

        List<PayOrder> payOrders = testService.getPayList(usernameToken.getUserId().toString(), page);
        JSONObject result = new JSONObject();
        result.put("status", "1");
        result.put("message", payOrders);
        return result;
    }

    /*
    *
    * 礼物列表
     */
    @RequestMapping(value = "/cashrecord", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ResponseBody
    public JSONObject cashRecord(HttpServletRequest request, HttpServletResponse response) throws IOException {
        response.setContentType("text/plain");
        response.setHeader("Pragma", "No-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);
        response.setHeader("Access-Control-Allow-Origin", "*");//添加跨域访问
        UsernameToken usernameToken = testService.getUser();
        if (usernameToken == null) {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("status", "0");
            jsonObject.put("message", "nologin");
            return jsonObject;
        }

        String page = request.getParameter("page");
        if (page.length() == 0) {
            page = "1";
        }

        JSONObject result = new JSONObject();
        List<GiftExchange> tiOrders = testService.getGiftlist(usernameToken.getUserId().toString(), page);
        result.put("status", "1");
        result.put("message", tiOrders);
        return result;
    }


}
